<template>
  <div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table :data="expandedRows" border style="width: 100%">
      <el-table-column width="50" label="选择">
        <template slot-scope="scope">
          <el-tooltip
            v-if="scope.row.children && scope.row.children.length > 0"
            class="item"
            effect="dark"
            :content="scope.row.isExpanded ? '收起' : '展开'"
            placement="top"
            width="120">
            <i :class="['el-icon', scope.row.isExpanded ? 'el-icon-arrow-down' : 'el-icon-arrow-right']"
               @click="toggleExpansion(scope.row)" style="cursor: pointer;"></i>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column label="类型名称">
        <template slot-scope="scope">
          <div :class="['indent-level-' + scope.row.level]">
            {{ scope.row.typeName }}
            <div v-if="scope.row.isExpanded && scope.row.children && scope.row.children.length > 0">
              <!-- 这里可以递归渲染子行，或者使用其他方式显示子行数据 -->
              <el-table :data="scope.row.children" style="width: 100%">
                <!-- 子行列定义 -->
              </el-table>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加类型的弹窗 -->
    <el-dialog title="添加类型列表" :visible.sync="openAddType" width="800px" append-to-body>
      <el-form ref="form" :model="formTreeData"  label-width="80px">
        <el-form-item label="父节点" prop="parentCode">
          <div style="width: 250px;height: 35px;
          border: 1px solid #cccccc;float: left;
          border-radius: 5px;
          text-align: center" @click="toggleTreeVisible" >{{typeName}}</div>
          <!-- 隐藏的下拉内容，用于显示树形结构 -->
          <el-dialog :visible.sync="treeVisible" width="300px" append-to-body>

            <el-tree
              :data="treeData"
              :props="defaultProps"
              node-key="typeCode"
              @node-click="handleNodeClick"
              :highlight-current="true"
              :show-checkbox="false"
              default-expand-all>
            </el-tree>
          </el-dialog>
        </el-form-item>
        <el-form-item label="类型名" prop="typeName" >
          <el-input v-model="formTreeData.typeName" type="text" placeholder="请输入类型名称" style="width: 200px"/>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddType">确 定</el-button>
        <el-button @click="cancelAddType">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 更新类型弹窗 -->
    <el-dialog title="更新类型列表" :visible.sync="openUpdateType" width="600px" append-to-body>
      <el-form ref="formTreeUpdateData" :model="formTreeUpdateData"  label-width="80px">
        <el-form-item label="父节点" prop="parentCode">
          <div style="width: 200px;height: 30px;border: 1px solid #cccccc;float: left;text-align: center" @click="toggleTreeVisible">{{typeNameByUpdate}}</div>
          <el-dialog :visible.sync="treeVisible" width="300px" append-to-body>
            <el-tree
              :data="treeData"
              :props="defaultProps"
              node-key="typeCode"
              @node-click="handleNodeClick"
              :highlight-current="true"
              :show-checkbox="false"
              default-expand-all>
            </el-tree>
          </el-dialog>
        </el-form-item>

        <el-form-item label="类型名" prop="typeName" >
            <el-input v-model="formTreeUpdateData.typeName" type="text" placeholder="请输入类型名称" style="width: 200px"/>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpdateType">确 定</el-button>
        <el-button @click="cancelUpdateType">取 消</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>
import {
  addTypeArticle,
  delTypeArticle,
  getTypeArticle,
  selectTreeType,
  updateTypeArticle
} from '@/api/shop/typeArticle'

export default {
  name: 'TreeView',
  data() {
    return {
      treeData: [],
      expandedRows: [],
      formTreeData:{},
      formTreeUpdateData:{},
      loading: true,
      openImageList:false,//图片默认关闭
      openAddType:false,// 新增弹窗默认关闭
      openUpdateType:false,//更新弹窗默认关闭
      selectedParent: null, // 用于v-model绑定
      defaultProps: {
        children: 'children',  // 修改为与后端数据一致的字段
        label: 'typeName'
      },
      treeVisible:false,
      title:"",
      typeName: "",
      typeNameByUpdate:""
    };
  },
  watch: {
    'formTreeUpdateData.parentCode'(newVal, oldVal) {
      this.selectedParent = newVal;
    },
    'selectedParent'(newVal, oldVal) {
      this.formTreeUpdateData.parentCode = newVal;
    }
  },
  mounted() {
    if (this.formTreeUpdateData && this.formTreeUpdateData.parentCode) {
      this.selectedParent = this.formTreeUpdateData.parentCode;
    }
  },
  created() {
    this.getListByType();
  },
  methods: {
    getListByType() {
      this.loading = true;
      selectTreeType().then(res => {
        this.treeData = res.data;
        console.log(this.treeData)
        this.processTreeData();
        this.loading = false;
      }).catch(error => {
        console.error('加载数据失败:', error);
        this.loading = false;
      });
    },

    processTreeData() {
      function calculateLevel(nodes, parentCode = 0, level = 1) {
        nodes.forEach(node => {
          node.level = level;
          if (node.childList) {
            calculateLevel(node.childList, node.typeCode, level + 1); // 递归计算子节点的层级
          }
        });
      }
      this.expandedRows = this.treeData.filter(node => !node.parentCode || node.parentCode === 0);
      calculateLevel(this.treeData);
      this.markHasChildren(this.treeData);
    },

    markHasChildren(nodes) {
      nodes.forEach(node => {
        node.hasChildren = node.childList && node.childList.length > 0;
        if (node.childList) {
          this.markHasChildren(node.childList);
        }
      });
    },
    toggleExpansion(row) {
      row.isExpanded = !row.isExpanded;
      if (row.isExpanded && row.children && row.children.length > 0) {
        this.expandedRows.push(...row.children.map(child => ({
          ...child,
          isExpanded: false,
        })));
      } else {
        this.expandedRows = this.expandedRows.filter(expandedRow => {
          return !(expandedRow.parentCode === row.typeCode);
        });
      }
    },
/*     toggleExpansion(row) {
      if (row.children && row.children.length > 0) {
        row.isExpanded = !row.isExpanded;
        // 如果需要，可以在这里处理子行的显示逻辑
      }
    }, */
    handleNodeClick(data, node, component) {
      this.selectedParent = data.typeCode;
      this.typeName = data.typeName;
      this.formTreeData.parentCode = this.selectedParent
      this.treeVisible = false; // 关闭对话框
    },
    toggleTreeVisible() {
      this.treeVisible = !this.treeVisible;
    },
    //修改弹窗
    handleUpdate(row){
      const id=row.id
      console.log(id)
      getTypeArticle(id).then(resp=>{
        this.formTreeUpdateData = resp.data
        console.log('根据id',this.formTreeUpdateData)
        this.typeNameByUpdate = this.formTreeUpdateData.typeName
        this.openUpdateType = true
      })
    },
    reset() {
      this.formTreeData = {
        typeName: null,
        parentCode: null,
      }

    },
    //新增
    handleAdd(){
      this.openAddType = true;
      this.title = "添加类型信息";
    },
    //删除
    handleDelete(row){
      const id = row.id
      this.$modal.confirm('是否确认删除该类型？').then(function(){
        return delTypeArticle(id);
      }).then(()=>{
        this.getListByType()
        this.$modal.msgSuccess("删除成功")
      }).catch(()=>{
        this.$modal.msgError("该父类下还有关联子类，不能删除")
      })
    },
    //确认新增类型
    submitAddType() {
      console.log("新增信息",this.formTreeData)
      //新增
      addTypeArticle(this.formTreeData).then(resp => {
        this.$modal.msgSuccess("新增成功")
        this.openAddType = false
        this.getListByType()
      })
      this.getListByType()
      this.reset()
    },
    //取消新增类型
    cancelAddType(){
      this.openAddType = false
    },
    //确认修改类型
    submitUpdateType(){
      //更新
      updateTypeArticle(this.formTreeUpdateData).then(response=>{
        this.$modal.msgSuccess("更新信息")
        this.openUpdateType = false
        this.getListByType()
      }).catch(error =>{
        console.error("更新失败",error)
      })
    },
    //取消更新类型
    cancelUpdateType(){
      this.openUpdateType = false
    },
  },
};
</script>
<style scoped>
.borderless .el-table__row,
.borderless .el-table__header-wrapper tr {
  border-bottom: none;
}

.borderless .el-table__body tr.el-table__row:last-child td {
  border-bottom: none;
}
</style>
